package com.hmall.search.task;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.pojo.Item;
import com.hmall.search.service.SearchService;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Description SearchTask
 * @Author GGBond
 * @Date 2024-11-15
 */

@Component
public class SearchTask {

    @Autowired
    private SearchService searchService;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 定时任务。每天凌晨3点执行，将销量前20的商品存入缓存
     * 路由模型-缓存
     */
    @Scheduled(cron = "0 0 3 * * *")
    @RabbitListener(bindings = @QueueBinding(value = @Queue(name = "cache.queue"),
            exchange = @Exchange(name = "hmmall.fanout",type = ExchangeTypes.FANOUT)))
    public void doTask() {
        System.out.println("==============================================");

        LambdaQueryWrapper<Item> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Item::getStatus,1).orderByDesc(Item::getSold);
        Page<Item> page = searchService.page(new Page<>(1, 20), wrapper);
        List<Item> records = page.getRecords();
        redisTemplate.opsForValue().set("product", JSONUtil.toJsonStr(records));
        redisTemplate.opsForValue().set("total", String.valueOf(page.getTotal()));
    }
}
